package com.example.csupermaket.service.impl;


import com.example.csupermaket.exception.ServiceException;
import com.example.csupermaket.mapper.AddressMapper;
import com.example.csupermaket.pojo.dto.AddressAddNewDTO;
import com.example.csupermaket.pojo.dto.AddressUpdateDTO;
import com.example.csupermaket.pojo.entity.Address;
import com.example.csupermaket.pojo.vo.AddressListItemVO;
import com.example.csupermaket.service.IAddressService;
import com.example.csupermaket.web.ServiceCode;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public void addNew(AddressAddNewDTO addressAddNewDTO) {

        Address address = new Address();
        BeanUtils.copyProperties(addressAddNewDTO,address);
        addressMapper.insert(address);

    }

    @Override
    public void deleteByAid(int aid) {

        if (addressMapper.countByAid(aid)>0){
            addressMapper.deleteByAid(aid);
        }else {
            String message = "删除地址失败，当前地址不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

    }

    @Override
    public void update(int aid,AddressUpdateDTO addressUpdateDTO) {
        int count = addressMapper.countByAid(aid);
        if (count>0){
            Address address = new Address();
            BeanUtils.copyProperties(addressUpdateDTO,address);
            addressMapper.update(address);
        }else {
            String message = "删除地址失败，当前地址不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
    }

    @Override
    public int countByAid(int aid) {
        int count = addressMapper.countByAid(aid);
        return count;
    }

    @Override
    public List<AddressListItemVO> selectByUid(int uid) {
        return addressMapper.selectByUid(uid);
    }
}
